<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { GetDataDetail, PostCreatePeo, PutDetailsRedact } from '@/api/modules/peopleManagement.ts'
import detailStore from '@/store/modules/cacheData'

const route = useRoute()
const router = useRouter()
const detailData = detailStore()
const id = route.query.id as string

const ruleFormRef = ref<FormInstance>()
const ruleForm: any = ref({
  account: '',
  password: '',
  mobile: 0,
  role: 2,
  enable: true,
  description: '',
  id: 0,
})
const roleArr = [
  { value: 2, label: '管理员' },
  { value: 3, label: '商务' },
  { value: 4, label: '运营' },
  { value: 5, label: '客服' },
  { value: 6, label: '财务' },
]

// 验证规则
const rules = reactive({
  account: [
    { required: true, message: '请输入账户名称', trigger: 'blur' },
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  role: [
    { required: true, message: '请选择身份', trigger: 'blur' },
  ],
})

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      if (id) {
        // 编辑
        PutDetailsRedact(ruleForm.value).then((res: any) => {
          if (res.succeeded) {
            ElMessage.success('修改成功')
            router.push({
              name: 'PeopleManagementIndex',
            })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`编辑失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`编辑失败。${errorStr}`)
            }
          }
        })
      }
      else {
        // 添加
        delete ruleForm.value.id
        PostCreatePeo(ruleForm.value).then((res: any) => {
          if (res.succeeded) {
            ElMessage.success('添加成功')
            detailData.EmptyPeople()
            router.push({
              name: 'PeopleManagementIndex',
            })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`添加失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`添加失败。${errorStr}`)
            }
          }
        })
      }
    }
  })
}

watch(ruleForm, (newValue) => {
  detailData.RememberPeople(newValue)
}, { deep: true })

onMounted(() => {
  if (id) {
    GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        // console.log(res)
        ruleForm.value = res.data
      }
      else {
        ElMessage.error(`获取信息失败。${res.errors}`)
      }
    })
  }
  else {
    ruleForm.value = detailData.GetPeopleData()
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '人员管理--编辑' : '人员管理--添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="账户名称" prop="account">
              <el-input v-model="ruleForm.account" style="width: 300px;" placeholder="请输入账户名称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="移动电话" prop="mobile">
              <el-input v-model="ruleForm.mobile" type="number" style="width: 300px;" placeholder="请输入移动电话" />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="!id" :md="8">
            <ElFormItem label="密码" prop="password">
              <el-input v-model="ruleForm.password" style="width: 300px;" placeholder="请输入密码" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="角色" prop="role">
              <el-radio-group v-model="ruleForm.role">
                <el-radio v-for="item in roleArr" :key="item.value" :value="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="状态" prop="enable">
              <ElRadioGroup v-model="ruleForm.enable">
                <ElRadioButton :value="true">
                  启用
                </ElRadioButton>
                <ElRadioButton :value="false">
                  禁用
                </ElRadioButton>
              </ElRadioGroup>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="备注" prop="description">
              <el-input v-model="ruleForm.description" style="width: 300px;" placeholder="请输入备注" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 60px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style scoped>
.avatar-uploader .avatar {
  display: block;
  width: 178px;
  height: 178px;
}

.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  width: 100px;
  height: 100px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}

.head {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  padding: 10px;
  font-size: 19px;
  background-color: white;
  border-bottom: 1px solid black;

  span {
    font-size: 20px;
  }
}

.from-list {
  position: relative;
  left: 3%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 20px;
  width: 95%;
  padding: 20px 30px;
  background-color: white;

  >div {
    min-height: 60px;
  }
}

.division {
  position: relative;
  left: 3%;
  width: 95%;
  padding: 10px 0 5px 10px;
  font-size: 19px;
  background-color: white;
  border-top: 1px solid darkgray;
  border-bottom: 1px dotted darkgray;
}
</style>
